今天的實作是要讓大家了解在JS裡的基本觀念,參照與複製。這堂課沒有介面也沒有什麼練習題目,所以就直接開始吧!
相信大家都看得懂下面這段code
let age = 100;
let age2 = age;
console.log(age, age2);//結果:100, 100
age = 200;
console.log(age, age2);//結果:200, 100
let name = 'Wes';
let name2 = name;
console.log(name, name2);//結果:Wes, Wes
name = 'wesley';
console.log(name, name2);//結果:wesley, Wes
當把變數指定給另一個變數,這時就會是兩個獨立的變數,當任一變數改變都不會影響另一變數,這是變數的複製。
但若發生在陣列或物件就不同了
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
const team = players;
console.log(players, team);
//結果:["Wes", "Sarah", "Ryan", "Poppy"],["Wes", "Sarah", "Ryan", "Poppy"]
team[3] = 'Lux';
console.log(players, team);
//結果:["Wes", "Sarah", "Ryan", "Lux"],["Wes", "Sarah", "Ryan", "Lux"]
若將陣列指定給另一變數,兩個都會指向同一陣列,因此當任一陣列改變,令一陣列也將被改變。
以下為幾種複製陣列的方法:
const team2 = players.slice();
const team3 = [].concat(players);
const team4 = [...players];
const team5 = Array.from(players);
同理,下面為複製物件的方法:
const person = {
name: 'Wes Bos',
age: 80
};
const cap2 = Object.assign({}, person);
要注意的是,若物件有超過一層,這種方法只會複製第一層,像下面範例,複製物件後改變某一物件第一層的name,另個name不受影響。但改變某一物件第二層的social.twitter,則兩個物件都被改變。
const wes = {
name: 'Wes',
age: 100,
social: {
twitter: '@wesbos',
facebook: 'wesbos.developer'
}
};
const cap3 = Object.assign({}, wes);
cap3.name="Bos";
console.log(wes.name);//結果:Wes
console.log(cap3.name);//結果:Bos
cap3.social.twitter="hahaha";
console.log(wes.social.twitter);//結果:hahaha
console.log(cap3.social.twitter);//結果:hahaha
若要完整複製,方法如下:
const dev = JSON.parse(JSON.stringify(wes));